# 图像查找
import cv2
import numpy as np

img1 = cv2.imread('E:\\opencv_photo\\opencv_search.png')
img2 = cv2.imread('E:\\opencv_photo\\opencv_orig.png')
# 灰度化
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
# 创建surf对象
surf = cv2.xfeatures2d.SURF_create()
# 计算特征点和描述子
kp1, des1 = surf.detectAndCompute(gray1, None)
kp2, des2 = surf.detectAndCompute(gray2, None)

# 创建匹配器
index_params = dict(algorithm = 1, trees = 5)
search_params = dict(checks = 50)
flann = cv2.FlannBasedMatcher(index_params, search_params)

#对描述子进行匹配计算
matchs = flann.knnMatch(des1, des2, k=2)

# 过滤，对所有匹配点进行优化
good = []
for i, (m,n) in enumerate(matchs):
    if m.distance < 0.7 * n.distance:
        good.append(m)

# ret = cv2.drawMatchesKnn(img1, kp1, img2, kp2, [good], None)

# 匹配点必须大于等于4
if len(good) >= 4:
# 查找单应性矩阵
    srcpts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1,1,2) 
    #对数组进行重新变换，有无数行，每一行有1个元素，每个元素由2个子元素组成
    dstpts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1,1,2) 

    H,_ = cv2.findHomography(srcpts, dstpts, cv2.RANSAC, 5.0)
    # 第三个参数是对匹配点进行过滤,随机抽样获取规律，最后一个参数为阈值
    # 第一个返回值为单应性矩阵，第二个参数为其掩码，不需要显示，所以用_代替

    # 透视变换
    h,w = img1.shape[:2]
    pts = np.float32([[0,0],[0,h-1], [w-1, h-1], [w-1, 0]]).reshape(-1,1,2)      # 四个角点，左上角，左下角,右下角，右上角
    dst = cv2.perspectiveTransform(pts, H)

    # 用多边形框起来
    cv2.polylines(img2, [np.int32(dst)], True,(0,255,255))
else:
    print('the number of good is less than 4.')
    exit()
# 绘制图像
ret = cv2.drawMatchesKnn(img1, kp1, img2, kp2, [good], None)
cv2.imshow('result',ret)
cv2.waitKey()